package com.cyys.modules.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyys.modules.core.controller.BaseAction;
import com.cyys.modules.core.sysParam.SystemConfigureUtil;
import com.cyys.modules.core.sysParam.SystemConstants;
import lombok.Cleanup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping("/file")
public class DownloadAction extends BaseAction {

	private static Logger logger = LoggerFactory.getLogger(DownloadAction.class);

	@ResponseBody
	@GetMapping(value = "/downloadFile")
	public void uploadFile(String fileUrl,String fileName) throws Exception {
		String basePath = SystemConfigureUtil.get(SystemConstants.FILE_ROOT_PATH);
		if (basePath.equals("")) {
			basePath = request.getSession().getServletContext().getRealPath("") + "files";
		}

		File f = new File(basePath + fileUrl);
		@Cleanup OutputStream out = response.getOutputStream();
		@Cleanup BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		byte[] buf = new byte[1024];
		int len = 0;
		response.reset(); // 非常重要
		response.setContentType("application/x-msdownload");
		//采用中文文件名需要在此处转码
		fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		while ((len = br.read(buf)) > 0)
			out.write(buf, 0, len);
	}

	@ResponseBody
	@GetMapping(value = "/downloadFiles")
	public void downloadFiles(String attachment, String zipName) throws Exception{
		String basePath = SystemConfigureUtil.get(SystemConstants.FILE_ROOT_PATH);
		if (basePath.equals("")) {
			basePath = request.getSession().getServletContext().getRealPath("") + "files";
		}

		//响应头的设置
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");

		if(zipName == null || zipName.equals("")){
			zipName = "压缩文件";
		}
		//设置压缩包的名字
		//解决不同浏览器压缩包名字含有中文时乱码的问题
		String downloadName = zipName + ".zip";
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent.contains("MSIE")||agent.contains("Trident")) {
				downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
			} else {
				downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

		//设置压缩流：直接写入response，实现边压缩边下载
		@Cleanup ZipOutputStream zipos = null;
		zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
		zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
		JSONArray jsonArray = JSONArray.parseArray(attachment);
		//循环将文件写入压缩流
		@Cleanup DataOutputStream os = null;
		for(int i = 0; i < jsonArray.size(); i++ ){
			JSONObject job = jsonArray.getJSONObject(i);
			File file = new File(job.getString(basePath + "fileAddr"));
			//添加ZipEntry，并ZipEntry中写入文件流
			//这里，加上i是防止要下载的文件有重名的导致下载失败
			zipos.putNextEntry(new ZipEntry(job.getString("fileName")));
			os = new DataOutputStream(zipos);
			@Cleanup InputStream is = new FileInputStream(file);
			byte[] b = new byte[100];
			int length = 0;
			while((length = is.read(b))!= -1){
				os.write(b, 0, length);
			}
		}
	}

}
